#include<stdio.h>
#include<pthread.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>

//将新连接描述符和客户端地址信息封装传给线程入口函数
struct cli_info{
    cli_info()
    :_new_sockfd(-1){
        memset(&addr, '0', sizeof(addr));
    }
    int _new_sockfd;
    struct sockaddr_in addr;
};

void* tcp_deal_start(void* arg){
    pthread_detach(pthread_self());
    cli_info* ci = (cli_info*)arg;
    int new_sockfd = ci->_new_sockfd;
    struct sockaddr_in cli_addr = ci->addr;
    //收发消息
    while(1){
        char buf[1024] = {0};
        int recv_size = recv(new_sockfd, buf, sizeof(buf) - 1, 0);
        if(recv_size < 0){
            perror("recb");
            continue;
        }else if(recv_size == 0){
            //客户端关闭连接
            printf("perr shutdown\n");
            delete ci;
            close(new_sockfd);
            return 0;
        }
        printf("[%s]:[%d] say [%s]\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port), buf);
        memset(buf, '\0', sizeof(buf));
        sprintf(buf, "[%s] : [%d] I am serve, I recv your msg", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
        send(new_sockfd, buf, strlen(buf), 0);
    }
}
int main(){
    int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(listen_fd < 0){
        perror("listen");
        return 0;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(22222);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    int ret = bind(listen_fd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret < 0){
       perror("bind");
       return 0;
    }
    ret = listen(listen_fd, 5);
    if(ret < 0){
        perror("listen");
        return 0;
    }

    //收发消息
    while(1){
        struct sockaddr_in cli_addr;
        socklen_t cli_addr_len = sizeof(cli_addr);
        int new_sockfd = accept(listen_fd, (struct sockaddr*)&cli_addr, &cli_addr_len);
        if(new_sockfd < 0){
            continue;
        }
        pthread_t tid;
        cli_info* ci = new cli_info();
        ci->_new_sockfd = new_sockfd;
        memcpy(&ci->addr, &cli_addr, sizeof(cli_addr));
        int ret = pthread_create(&tid, NULL, tcp_deal_start, (void*)ci);
        if(ret < 0){
            close(new_sockfd);
            continue;
        }
    }
    return 0;
}
